
package com.directthought.elasticweb;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.ServerSocket;
import java.net.UnknownHostException;

import org.apache.log4j.Logger;

/**
 * This class listens on a port, accepts connection and simply writes a 0 byte back.
 */
public class MockHTTPListener extends Thread {
	private static Logger logger = Logger.getLogger(MockHTTPListener.class);
	public static final int HTTP_SOCKET = 8080;
	private String instanceId;

	public MockHTTPListener(String instanceId) {
		this.instanceId = instanceId;
	}

	public void run() {
		while (true) {
			try {
				ServerSocket ss = new ServerSocket(HTTP_SOCKET);
				while (true) {
					Socket sock = ss.accept();
					InputStream iStr = sock.getInputStream();
					String hostToCheck = new BufferedReader(new InputStreamReader(iStr)).readLine();
					// ping that host, and reply
					String body = "<html><head><META HTTP-EQUIV=\"Pragma\" CONTENT=\"no-cache\"><META HTTP-EQUIV=\"Expires\" CONTENT=\"-1\"></head><body>Mock HTTP Server is ALIVE<p/>"+instanceId+"</body></html>\n";
					OutputStream oStr = sock.getOutputStream();
					oStr.write("HTTP/1.1 200 OK\n".getBytes());
					oStr.write("Date: Mon, 10 Sep 2007 16:49:54 GMT\n".getBytes());
					oStr.write("Server: MockHTTP\n".getBytes());
					oStr.write("Transfer-Encoding: identity\n".getBytes());
					oStr.write(("Content-Length: "+body.length()+"\n").getBytes());
					oStr.write("Content-Type: text/html\n".getBytes());
					oStr.write("\n".getBytes());
					oStr.write(body.getBytes());
					oStr.write("\n0\n\n".getBytes());
					oStr.flush();
					sock.close();
				}
			} catch (Exception ex) {
				logger.error("problem accepting connection. will keep going.", ex);
			}
		}
	}
}
